package com.rjkj.medicalwaste.ui.storage

import android.app.AlertDialog
import android.content.DialogInterface
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.rjkj.medicalwaste.MainActivity
import com.rjkj.medicalwaste.R
import com.rjkj.medicalwaste.base.BaseFragment
import com.rjkj.medicalwaste.base.checkState
import com.rjkj.medicalwaste.bean.GarbageBean
import com.rjkj.medicalwaste.bean.GarbageStatus
import com.rjkj.medicalwaste.database.GarbageSetStorage
import com.rjkj.medicalwaste.databinding.FragmentStorageFunctionBinding
import com.rjkj.medicalwaste.livedatabus.LiveDataBus
import com.rjkj.medicalwaste.network.response.next
import com.rjkj.medicalwaste.utils.TimeUtils
import com.rjkj.medicalwaste.viewmodels.UnBoxedViewModel
import com.rjkj.medicalwaste.viewmodels.UserViewModel
import com.rjkj.medicalwaste.viewmodels.provider.MainViewModelProvider
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


class StorageFunctionFragment : BaseFragment<FragmentStorageFunctionBinding>() {
    private var reviewWeightDialog: ReviewWeightDialog? = null
    private var unReviewWeightDialog: UnReviewWeightDialog? = null
    private val userViewModel: UserViewModel by activityViewModels {
        MainViewModelProvider.provideUserModel(requireContext())
    }
    private val unBoxedViewModel: UnBoxedViewModel by viewModels {
        MainViewModelProvider.provideUnBoxedModel(requireContext())
    }


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val binding = FragmentStorageFunctionBinding.inflate(inflater, container, false)
        binding.userData = userViewModel
        binding.lifecycleOwner = viewLifecycleOwner
        onSubscribeUi(binding)
        return binding.root
    }


    override fun onSubscribeUi(binding: FragmentStorageFunctionBinding) {
        initDialog(userViewModel)
        initTip(unBoxedViewModel)
        //同步垃圾数据监听
        userViewModel.uploadUser.observe(viewLifecycleOwner) {
            if (it != null) {
                lifecycleScope.launch {
                    userViewModel.uploadEvent.value = true
                    val reviewNotBoxGarbageByCleaner =
                        unBoxedViewModel.getReviewNotBoxGarbageByCleaner(
                            userViewModel.getUrl(),
                            cleanerQRCode = it.qrcode,
                            hospitalId = userViewModel.hospitalId.value ?: "",
                            reviewStorageQRCode = userViewModel.stagingRoomUser.value?.qrcode ?: "",
                            serialNum = userViewModel.getSerial()
                        )
                    if (reviewNotBoxGarbageByCleaner != null) {
                        for (value in reviewNotBoxGarbageByCleaner) {
                            val departmentQRCodeName =
                                userViewModel.findUserByQrCode(value.departmentQRCode)?.name ?: ""
                            val nurseQRCodeName =
                                userViewModel.findUserByQrCode(value.nurseQRCode)?.name ?: ""
                            val cleaner =
                                userViewModel.findUserByQrCode(value.cleanerQRCode)
                            val cleanerQRCodeName =
                                cleaner?.name ?: ""
                            value.apply {
                                garbageUserStatus = GarbageStatus.loading
                                reviewType = "0"
                                hospitalName = cleaner?.hospitalName?:""
                                cleanerName = cleanerQRCodeName
                                departmentName = departmentQRCodeName
                                nurseQRName = nurseQRCodeName
                            }
                            unBoxedViewModel.repository.insertGarbage(value)
                        }
                    }
                    showTip("同步成功")
                    userViewModel.uploadEvent.value = false
                    userViewModel.uploadUser.value = null
                }
            }

        }

        if (!unBoxedViewModel.firstLoad) {
            lifecycleScope.launchWhenStarted {
                unBoxedViewModel.firstLoad = true
                val time = TimeUtils.getYMDHMSTime()
                val stagingRoomCode = userViewModel.stagingRoomUser.value?.qrcode ?: ""
                val cleaner = userViewModel.cleanerUser.qrcode
                val stateGarbage = unBoxedViewModel.repository.getStateGarbage(
                    userViewModel.hospitalId.value
                        ?: "",
                    GarbageStatus.collect
                )
                for (garbage in stateGarbage) {
                    garbage.storageTime = time
                    garbage.reviewStorageQRCode = stagingRoomCode
                    garbage.reviewDeviceSN = userViewModel.getSerial()
                    garbage.reviewWeight = garbage.garbageWeight
                    garbage.reviewTime = time
                    garbage.reviewCleanerQRCode = cleaner
                }
                val map = stateGarbage.map { garbageBean ->
                    GarbageSetStorage(
                        id = garbageBean.id,
                        garbageQRCode = garbageBean.garbageQRCode,
                        storageTime = garbageBean.storageTime,
                        reviewStorageQRCode = garbageBean.reviewStorageQRCode,
                        reviewDeviceSN = garbageBean.reviewDeviceSN,
                        reviewWeight = garbageBean.garbageWeight,
                        reviewTime = garbageBean.reviewTime,
                        reviewCleanerQRCode = garbageBean.reviewCleanerQRCode,
                    )
                }
                if (stateGarbage.isNotEmpty()) {
                    val updateGarbageSetStorageNum =
                        unBoxedViewModel.repository.updateGarbageSetStorage2(map)
                    userViewModel.uploadGarbage(
                        garbageBeanList = stateGarbage,
                        successState = GarbageBean.storeState,
                        failState = GarbageBean.nullState
                    )
                    if (updateGarbageSetStorageNum > 0)
                        unBoxedViewModel.tips.value = ("入库成功${updateGarbageSetStorageNum}条数据")
                } else {
                    unBoxedViewModel.tips.value = ("没有可以入库的数据")
                }
            }
        }

        LiveDataBus.get().with(MainActivity.SCAN_DATA, String::class.java).observe(
            viewLifecycleOwner, {
                Log.e(TAG, "onSubscribeUi: $it")
                if (it.length >= 74 || it.length == 49) {
                    val code = if(it.length==49){"1" + it.split("?").last()}else{it.split("?").last()}
                    lifecycleScope.launch {
                        val findGarbageByCodeAndStatus =
                            unBoxedViewModel.repository.findGarbageByCode2(code)
                        if (findGarbageByCodeAndStatus != null) {
                            if (findGarbageByCodeAndStatus.reviewStorageQRCode != userViewModel.stagingRoomUser.value?.qrcode ?: "") {
                                showTip("医废不属于该暂存间")
                                return@launch
                            }
                            if (findGarbageByCodeAndStatus.garbageUserStatus == GarbageStatus.loading) {
                                if (userViewModel.setting.value?.review == true) {//复核模式
                                    if (reviewWeightDialog != null && reviewWeightDialog!!.showsDialog) {
                                        parentFragmentManager.findFragmentByTag("ReviewWeightDialog")
                                            ?.let { dialog ->
                                                (dialog as DialogFragment).dismiss()
                                            }
                                    }
                                    reviewWeightDialog = ReviewWeightDialog().apply {
                                        val bundle = Bundle()
                                        bundle.putString(BoxListFragment.GARBAGE_TYPE, code)
                                        this.arguments = bundle
                                        setStyle(
                                            DialogFragment.STYLE_NORMAL,
                                            R.style.dialogNormal
                                        )//添加上面创建的style
                                    }
                                    reviewWeightDialog!!.show(
                                        parentFragmentManager,
                                        "ReviewWeightDialog"
                                    )

                                } else {//不复核模式
                                    if (unReviewWeightDialog != null && unReviewWeightDialog!!.showsDialog) {
                                        parentFragmentManager.findFragmentByTag("unReviewWeightDialog")
                                            ?.let { dialog ->
                                                (dialog as DialogFragment).dismiss()
                                            }
                                    }
                                    unReviewWeightDialog = UnReviewWeightDialog().apply {
                                        val bundle = Bundle()
                                        bundle.putString(BoxListFragment.GARBAGE_TYPE, code)
                                        this.arguments = bundle
                                        setStyle(
                                            DialogFragment.STYLE_NORMAL,
                                            R.style.dialogNormal
                                        )//添加上面创建的style
                                    }
                                    unReviewWeightDialog!!.show(
                                        parentFragmentManager,
                                        "unReviewWeightDialog"
                                    )
                                }
                            } else {
                                showTip("无法添加${checkState(findGarbageByCodeAndStatus.garbageUserStatus)}状态")
                            }
                        } else {
                            showTip("未找到有效医废信息")
                        }
                    }
                } else {
                    showTip("请扫描医废二维码")
                }

            })
//        lifecycleScope.launch(Dispatchers.IO) {
//            unBoxedViewModel.createBox(userViewModel.stagingRoomUser.value?: UserBean(),userViewModel.cleanerUser)
//        }
        userViewModel.hospitalId.value?.let {
            unBoxedViewModel.getStateGarbageByStoreCodeToList(
                it, GarbageStatus.loading, userViewModel.stagingRoomUser.value?.qrcode
                    ?: ""
            ).observe(viewLifecycleOwner, { list ->
                binding.tvNum.text = list.size.toString()
            })
        }
        binding.btAddBag.setOnClickListener {
            findNavController().navigate(R.id.action_storageFunctionFragment_to_storageMainFragment)
        }
        binding.btCloseBox.setOnClickListener {
            findNavController().navigate(R.id.action_storageFunctionFragment_to_boxListFragment)
        }
        binding.btFinish.setOnClickListener {
            lifecycleScope.launch {
                userViewModel.uploadEvent.value = (true)
                val multiStateGarbageBeanList = unBoxedViewModel.getMultiStateGarbageBeanList(
                    userViewModel.hospitalId.value
                        ?: "", userViewModel.stagingRoomUser.value?.qrcode
                        ?: "", arrayOf(GarbageStatus.boxed)
                )
                Log.e(TAG, "onSubscribeUi: $multiStateGarbageBeanList")

                if (multiStateGarbageBeanList.isNotEmpty()) {
                    userViewModel.uploadGarbage(
                        garbageBeanList = multiStateGarbageBeanList,
                        successState = GarbageBean.boxState,
                        failState = GarbageBean.nullState
                    )

                    showTip("完工成功")
                    delay(1000L)
                    requireActivity().onBackPressed()
                } else {
                    delay(1000L)
                    showTip("暂无数据")
                    userViewModel.uploadEvent.value = (false)
                }
            }

//            unBoxedViewModel.getBoxWithGarbageList()
//            findNavController().navigate(R.id.action_storageFunctionFragment_to_storageCanFragment)
        }
        binding.btSync.setOnClickListener {
            findNavController().navigate(R.id.action_storageFunctionFragment_to_scanUserFragment)

        }
    }


}